//
//  ViewController.m
//  AVPlayertest
//
//  Created by lzy on 17/2/7.
//  Copyright © 2017年 NumberFive. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LLPlayerView.h"

static const NSString *content;

@interface ViewController ()<LLPlayerProtocol>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *layerBack;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayerItem *item;

@property (nonatomic, strong) LLPlayerView *playerView;

@end

@implementation ViewController {
    AVAsset *asset;
    id _obj;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"hubblecast" withExtension:@"m4v"];
    asset = [AVAsset assetWithURL:url];
    
    CGSize size = asset.naturalSize;
    NSLog(@"%@",@(size.width));
    
    //self.item = [AVPlayerItem playerItemWithURL:url];
    self.item = [AVPlayerItem playerItemWithAsset:asset];
    
    [self.item addObserver:self
           forKeyPath:@"status"
              options:0
              context:&content];
    
    self.player = [AVPlayer playerWithPlayerItem:self.item];
//    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//    [self.layerBack.layer addSublayer:self.playerLayer];

    [self.layerBack addSubview:self.playerView];
    self.playerView.frame = self.layerBack.bounds;
    self.playerView.player = self.player;
    
    ///时间
    CMTime duration =asset.duration;
    NSUInteger second = CMTimeGetSeconds(duration);
    self.playerView.durtionTime.text = [NSString stringWithFormat:@"%@",@(second)];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.playerLayer.frame = self.layerBack.bounds;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    if (context == &content) {
        
        [self.item removeObserver:self
                       forKeyPath:@"status"
                          context:&content];
        if (self.item.status == AVPlayerItemStatusReadyToPlay) {
            
            NSArray *items =
            [AVMetadataItem metadataItemsFromArray:asset.commonMetadata
                                           withKey:AVMetadataCommonKeyTitle
                                          keySpace:AVMetadataKeySpaceCommon];
            if (items.count > 0) {
                AVMetadataItem *titleItem = [items firstObject];
                self.titleLabel.text = (NSString *)titleItem.value;
            }
            
            [self.player play];
            [self timeLine];
            
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                CMTime interval =
                CMTimeMakeWithSeconds(7, NSEC_PER_SEC);
                [self.player seekToTime:interval
                      completionHandler:^(BOOL finished) {
                          NSLog(@"%@",@(finished));
                      }];
            });
            
        }
    }

}

- (LLPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [LLPlayerView playerView];
        _playerView.delegate = self;
    }
    return _playerView;
}

- (void)timeLine {
    CMTime interval =
    CMTimeMakeWithSeconds(1, NSEC_PER_SEC);
    dispatch_queue_t queue = dispatch_get_main_queue();
    __weak ViewController *weakSelf = self;
    void (^callback)(CMTime time) = ^(CMTime time)
    {
        NSUInteger currentTime = CMTimeGetSeconds(time);
        NSUInteger duration = CMTimeGetSeconds(weakSelf.item.duration);
        
        weakSelf.playerView.durtionTime.text = [NSString stringWithFormat:@"%@",@(duration - currentTime)];
        
        if (duration - currentTime == 0)
        {
            [self.player removeTimeObserver:_obj];
            _obj = nil;
        }
    };
    _obj = [self.player addPeriodicTimeObserverForInterval:interval
                                              queue:queue usingBlock:callback];
}

- (void)pauseButtonClicked {
    if (self.player.rate == 0) {
        [self.player play];
    } else {
        [self.player pause];
    }
}

@end
